package com.binance.actuator.config;

import java.util.HashMap;
import java.util.Map;

import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.HealthAggregator;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import com.binance.actuator.indicator.RedisHealthIndicator;

import redis.clients.jedis.Jedis;

/**
 * Created by robin.wu on 2018/11/14.
 */
@Configuration
@ConditionalOnClass(Jedis.class)
@AutoConfigureAfter(value = RedisAutoConfiguration.class)
@ConditionalOnProperty(value = "com.binance.actuator.health.enhance.enable", havingValue = "true")
public class ActuatorRedisAutoConfig {

    private final Map<String, RedisConnectionFactory> redisConnectionFactories;
    @Autowired
    private HealthAggregator healthAggregator;


    public ActuatorRedisAutoConfig(Map<String, RedisConnectionFactory> redisConnectionFactories){
        this.redisConnectionFactories = redisConnectionFactories;
    }

    @Bean
    @ConditionalOnClass(value = {RedisConnectionFactory.class})
    @ConditionalOnMissingBean(name = "redisHealthIndicator")
    public HealthIndicator redisHealthIndicator() {
        Map<String, RedisConnectionFactory> objRedisConnectionFactories = new HashMap<>();
        for (String name : redisConnectionFactories.keySet()) {
            if(! (redisConnectionFactories.get(name) instanceof RedissonConnectionFactory)) {
                objRedisConnectionFactories.put(name,redisConnectionFactories.get(name));
            }
        }
        return RedisHealthIndicator.createHealthIndicator(objRedisConnectionFactories,healthAggregator);
    }
}
